<?php

namespace App\ModelFilters;

use Carbon\Carbon;
use EloquentFilter\ModelFilter;

/**
 * @method whereLike(string $string, $value)
 */
class BaseModelFilter extends ModelFilter
{
    public function id($value) {
        if (is_array($value)) {
            return $this->whereIn('id', $value);
        } else {
            return $this->where('id', $value);
        }
    }

    /**
     * 创建日期
     * @param $date
     * @return $this
     */
    public function start($date)
    {
        $date = Carbon::parse($date);
        return $this->where('created_at', '>=', $date);
    }

    /**
     * 创建结束时间
     * @param $date
     * @return $this
     */
    public function end($date)
    {
        $date = Carbon::parse($date);
        $date = $date->addDay();
        return $this->where('created_at', '<', $date);
    }

    /**
     * 创建开始时间
     * @param $date
     * @return $this
     */
    public function startCreatedAt($date)
    {
        $date = Carbon::parse($date);
        return $this->where('created_at', '>=', $date);
    }

    /**
     * 创建结束时间
     * @param $date
     * @return $this
     */
    public function endCreatedAt($date)
    {
        $date = Carbon::parse($date);
        return $this->where('created_at', '<', $date);
    }

    /**
     * 创建日期
     * @param $date
     * @return $this
     */
    public function updatedStart($date)
    {
        $date = Carbon::parse($date);
        return $this->where('updated_at', '>=', $date);
    }

    /**
     * 创建结束时间
     * @param $date
     * @return $this
     */
    public function updatedEnd($date)
    {
        $date = Carbon::parse($date);
        $date = $date->addDay();
        return $this->where('updated_at', '<', $date);
    }

    /**
     * 公共排序入口
     * @param $column
     * @return BaseModelFilter
     */
    public function sort($column)
    {
        if (is_array($column)) {
            $that = $this;
            foreach ($column as $key => $desc) {
                $that->orderBy($key, $desc);
            }
            return $that;
        }
        return $this->orderBy($column, $this->input('dir', 'asc'));
    }

    /**
     * 随机
     * @param $value
     * @return BaseModelFilter
     */
    public function random($value)
    {
        if  ($value) {
            return $this->inRandomOrder();
        }
    }


    /**
     * @param $value
     * @return BaseModelFilter
     */
    public function softDelete($value)
    {
        if  ($value) {
            return $this->onlyTrashed();
        }
    }
}
